package com.xujl.task.follow;

import com.xujl.task.RxLog;
import com.xujl.task.consts.FollowType;

import java.util.LinkedHashMap;
import java.util.Set;

/**
 * 步骤队列执行器
 */
public class QueueActuator implements IActuator, ITrigger {
    private static final String TAG = "QueueActuator";
    private RxFollow mControl;
    /**
     * 当前步骤
     */
    private int mCurrentStep = -1;
    private int mState = FollowType.STEP_WAIT;

    @Override
    public void init (RxFollow control) {
        mControl = control;
    }

    @Override
    public void start () {
        final int nextStep = getNextStep();
        //是否已经全部执行完
        if (nextStep == -1) {
            mState = FollowType.STEP_COMPLETE;
            RxLog.i(TAG, "STEP_COMPLETE");
            return;
        }
        final IFollowStep nextFollow = getNextFollow(nextStep);
        mCurrentStep = nextStep;
        mState = FollowType.STEP_RUN;
        RxLog.i(TAG, "STEP_RUN");
        nextFollow.run(this);
    }

    private IFollowStep getNextFollow (int nexStep) {
        return mControl.getFollowSteps().get(nexStep);
    }

    private int getNextStep () {
        final LinkedHashMap<Integer, IFollowStep> followSteps = mControl.getFollowSteps();
        final Set<Integer> keySet = followSteps.keySet();
        boolean findFlag = false;
        for (Integer step : keySet) {
            if (mState == FollowType.STEP_WAIT) {
                return step;
            }
            if (findFlag) {
                return step;
            }
            if (step == mCurrentStep) {
                findFlag = true;
            }
        }
        return -1;
    }


    @Override
    public void followComplete () {
        start();
    }

    @Override
    public void followError () {

    }

    @Override
    public void followSaveResult (int code, Object data) {
        mControl.getStepData().put(code, data);
    }

    @Override
    public <T> T getStepResult (int code) {
        return mControl.getStepResult(code);
    }
}
